package thread.excese;

import java.util.Objects;

public class Demo2 {
    public static void main(String[] args) {
       Bank[] banks = new Bank[100];
       banks[0] = new Bank(2000,"123");
       banks[1] = new Bank(2000,"456");
       banks[2] = new Bank(2000,"789");
        Thread t1 = new Thread(()->{banks[0].transfer(banks[1],2000);});
        Thread t2 = new Thread(()->{banks[0].transfer(banks[1],2000);});
        t1.start();
        t2.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(banks[0].getAccount()+":"+banks[0].getMoney());
        System.out.println(banks[1].getAccount()+":"+banks[1].getMoney());
        System.out.println(banks[2].getAccount()+":"+banks[2].getMoney());

    }
}
class Bank{
    private  int monyey;
    private  String account;

    public Bank(int monyey, String account) {
        this.monyey = monyey;
        this.account = account;
    }

    public Bank() {
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Bank bank = (Bank) o;
        return monyey == bank.monyey && Objects.equals(account, bank.account);
    }

    @Override
    public int hashCode() {
        return Objects.hash(monyey, account);
    }

    public synchronized void transfer(Bank b, int money) {
        int balance = this.getMoney();
        if(balance >= money){
            balance = balance - money;
            save(balance);
            gather(b,money);
            System.out.println("转账成功！");
        }else {
            System.out.println("余额不足！");
        }
    }
    
    public int getMoney() {
        return monyey;
    }

    public void setMonyey(int monyey) {
        this.monyey = monyey;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public void save(int money) {
        this.monyey = money;
    }
    public void gather(Bank b,int money) {
        b.save(b.getMoney()+money);
    }
}
